﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NHibernate;
using NHibernate.Criterion;

using BOSS.Framework.Search.Context;
using BOSS.Domain.Products;
using BOSS.Dao.Products;

namespace BOSS.Dao.NHibernate.Products
{
    public class ConsumptionRecordDao : EntityDao<ConsumptionRecord, int>, IConsumptionRecordDao
    {
        #region ISearchSupport<ConsumptionRecord> 成员

        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="context"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public IList<ConsumptionRecord> SelectBySearch(ISearchContext context, out int totalCount)
        {
            int count = 0;

            IList<ConsumptionRecord> consumptionRecords = this.HibernateTemplate.ExecuteFind<ConsumptionRecord>(delegate(ISession session)
            {
                ICriteria criteria = session.CreateCriteria(typeof(ConsumptionRecord), "cr");

                DateTime? createTimeMin = context.GetFilterRangeMinValueAsDateTime("CreateTime");
                DateTime? createTimeMax = context.GetFilterRangeMaxValueAsDateTime("CreateTime");

                if (createTimeMin != null)
                {
                    criteria.Add(Expression.Gt("cr.CreateTime", createTimeMin.Value.Date));
                }

                if (createTimeMax != null)
                {
                    criteria.Add(Expression.Le("cr.CreateTime", createTimeMax.Value.AddDays(1).Date));
                }

                count = criteria.SetProjection(Projections.Count("Id").SetDistinct()).UniqueResult<int>();
                if (count == 0)
                {
                    return new List<ConsumptionRecord>();
                }

                criteria.SetProjection(new IProjection[] { null });
                criteria.SetResultTransformer(CriteriaSpecification.DistinctRootEntity);

                return criteria.SetFirstResult(context.PageSize * (context.PageIndex - 1))
                        .SetMaxResults(context.PageSize)
                        .List<ConsumptionRecord>();
            });

            totalCount = count;
            return consumptionRecords;
        }

        #endregion
    }
}
